/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.personal.controller;

import com.koron.accident.util.BusinessCode;
import com.koron.common.Excel;
import com.koron.common.StaffAttribute;
import com.koron.common.bean.DeptBean;
import com.koron.common.bean.StaffBean;
import com.koron.common.domain.DataBean;
import com.koron.common.permission.SPIAccountAnno;
import com.koron.common.web.Util;
import com.koron.personal.domain.MyCertificate;
import com.koron.personal.service.api.MyCertificateService;
import com.koron.system.annotation.Log;
import com.koron.system.discrete.BusinessManipulation;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.swan.bean.MessageBean;
import springfox.documentation.annotations.ApiIgnore;

import java.io.File;
import java.io.InputStream;
import java.util.*;

@Api(tags = "MyCertificate", description = "我的证照接口类")
@RestController
@RequestMapping("/myCertificate")
public class MyCertificateController {

    @Autowired
    private MyCertificateService service;

    @Autowired
    private Util util;

    @ApiOperation("保存我的证照接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id，新增不传，修改必传", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "corpCode", value = "水司code", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "staffCode", value = "选择上传人员code", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "staffName", value = "选择上传人员code", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "certificateName", value = "证件名称", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "certificateType", value = "证照类型", required = true, dataType = "String", paramType = "query"),
           // @ApiImplicitParam(name = "dutiesId", value = "职责id", dataType = "String", paramType = "query"),
           // @ApiImplicitParam(name = "dutiesName", value = "职责名称", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "jobsStaffCertificateId", value = "人员必须持证id", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "period", value = "证件有效截止期,格式为：yyyy-MM-dd", required = true, dataType = "long", paramType = "query"),
            @ApiImplicitParam(name = "certificateCode", value = "证件编号", dataType = "String", paramType = "query"),
            //@ApiImplicitParam(name = "type", value = "类型：0，安全管理员上传，1，自己上传", dataType = "int", paramType = "query"),
    })
    @RequestMapping(value = "/save.htm", method = RequestMethod.POST)
    @Log(title = "新增、修改我的证照", businessModule = "我的证照", businessManipulation = BusinessManipulation.INSERT)
    public MessageBean<Integer> save(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @ApiIgnore MyCertificate bean,
                                     @RequestParam(required = false) final String keepFiles, @RequestParam(required = false) final String delFiles,
                                     @RequestParam(required = false) final MultipartFile[] files) {
        if (null == user) {
            MessageBean<Integer> messageBean = new MessageBean<>();
            messageBean.setCode(BusinessCode.NOT_LONGIN.getCode());
            messageBean.setDescription(BusinessCode.NOT_LONGIN.getDescription());
            return messageBean;
        }
        if (StringUtils.isEmpty(bean.getStaffCode())){
            bean.setStaffName(user.getName());
            bean.setStaffCode(user.getCode());
        }
        List<DeptBean> deptBeanList = (List<DeptBean>) util.dept(bean.getStaffCode().split("_")[0]).getData();
        bean.setType(1);
        bean.setDeptCode(deptBeanList.get(0).getCode());
        return service.save(bean, keepFiles, delFiles, files);
    }


    @ApiOperation("删除我的证照接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "我的证照id", required = true, dataType = "String", paramType = "query"),
    })
    @RequestMapping(value = "/delete.htm", method = RequestMethod.POST)
    @Log(title = "删除我的证照", businessModule = "我的证照", businessManipulation = BusinessManipulation.DELETE)
    public MessageBean<Integer> delete(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestParam final String id) {
        if (null == user) {
            MessageBean<Integer> messageBean = new MessageBean<>();
            messageBean.setCode(BusinessCode.NOT_LONGIN.getCode());
            messageBean.setDescription(BusinessCode.NOT_LONGIN.getDescription());
            return messageBean;
        }
        return service.delete(id);
    }

    @ApiOperation("查询单个我的证照接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "我的证照id", required = true, dataType = "String", paramType = "query"),
    })
    @RequestMapping(value = "/details.htm", method = RequestMethod.POST)
    public MessageBean<MyCertificate> details(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestParam final String id) {
        if (null == user) {
            MessageBean<MyCertificate> messageBean = new MessageBean<>();
            messageBean.setCode(BusinessCode.NOT_LONGIN.getCode());
            messageBean.setDescription(BusinessCode.NOT_LONGIN.getDescription());
            return messageBean;
        }
        return service.queryOne(id);
    }

    @ApiOperation("我的证照列表接口")
    @ApiImplicitParams({
            //@ApiImplicitParam(name = "userCode", value = "用户code,pc不传，app必传", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "keyword", value = "关键词", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "当前页", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", required = true, dataType = "int", paramType = "query"),
    })
    @RequestMapping(value = "/list.htm", method = RequestMethod.POST)
    public MessageBean<DataBean<MyCertificate>> list(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user,@RequestParam(required = false) String keyword, @RequestParam Integer page, @RequestParam Integer pageSize) {
        MessageBean<DataBean<MyCertificate>> msg = new MessageBean<>();
        if (null == user) {
            msg.setCode(BusinessCode.NOT_LONGIN.getCode());
            msg.setDescription(BusinessCode.NOT_LONGIN.getDescription());
            return msg;
        }
        Integer start = null;
        if (page == null || page <= 0) {
            page = 1;
            if (pageSize == null || pageSize <= 0) {
                pageSize = 15;
            }
        }
        start = (page <= 1) ? 0 : (page - 1) * pageSize;
        msg = service.list(user.getCode(), start, pageSize,keyword);
        if (null != msg.getData())
            msg.getData().setPageNo(page);
        return msg;
    }

    @ApiOperation("选择证照列表的接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userCode", value = "用户code,pc不传，app必传", dataType = "String", paramType = "query"),
    })
    @RequestMapping(value = "/queryRequiredCertificate.htm", method = RequestMethod.POST)
    public MessageBean<?> queryRequiredCertificate(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestParam(required = false) final String userCode) {
        MessageBean<?> msg = new MessageBean<>();
        if (user == null) {
            List<StaffBean> staffBeanList = (List<StaffBean>) util.staff(userCode, null).getData();
            if (null != staffBeanList && staffBeanList.size() > 0)
                user = staffBeanList.get(0);
        }
        if (null == user) {
            msg.setCode(BusinessCode.NOT_LONGIN.getCode());
            msg.setDescription(BusinessCode.NOT_LONGIN.getDescription());
            return msg;
        }
        return service.queryRequiredCertificate(user.getCode());
    }

    @ApiOperation("选择岗位工种的接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userCode", value = "用户code,pc不传，app必传", dataType = "String", paramType = "query"),
    })
    @RequestMapping(value = "/queryDuties.htm", method = RequestMethod.POST)
    public MessageBean<?> queryDuties(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestParam(required = false) final String userCode) {
        MessageBean<?> msg = new MessageBean<>();
        if (user == null) {
            List<StaffBean> staffBeanList = (List<StaffBean>) util.staff(userCode, null).getData();
            if (null != staffBeanList && staffBeanList.size() > 0)
                user = staffBeanList.get(0);
        }
        if (null == user) {
            msg.setCode(BusinessCode.NOT_LONGIN.getCode());
            msg.setDescription(BusinessCode.NOT_LONGIN.getDescription());
            return msg;
        }
        return service.queryDuties(user.getCode());
    }

    @ApiOperation("人员持证---导入证照")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userCode", value = "人员code", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "corpCode", value = "水司code", dataType = "String", paramType = "query"),
    })
    @RequestMapping(value = "/importFromExcel.htm", method = RequestMethod.POST)
    public MessageBean<Boolean> importFromExcel(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, String userCode, MultipartFile file, String corpCode) throws Exception {
        MessageBean<Boolean> msg = new MessageBean<>();
        if (user == null) {
            List<StaffBean> staffBeanList = (List<StaffBean>) util.staff(userCode, null).getData();
            if (null != staffBeanList && staffBeanList.size() > 0)
                user = staffBeanList.get(0);
        }
        if (null == user) {
            msg.setCode(BusinessCode.NOT_LONGIN.getCode());
            msg.setDescription(BusinessCode.NOT_LONGIN.getDescription());
            return msg;
        }
        return service.importFromExcel(user, file, corpCode);
    }

    @ApiOperation(value = "下载证照导入模板")
    @RequestMapping(value = "/downloadtemplate.htm", method = {RequestMethod.GET})
    public HttpEntity<?> exportTemplate(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user) {
        if (null == user) {
            return null;
        }
        Map<String, Object> map = new HashMap<>();
        File targetFile = new File("static/excel/certificateTemplate.xlsx");
        try {
            InputStream in = getClass().getClassLoader().getResourceAsStream("static/excel/certificateTemplate.xlsx");
            FileUtils.copyInputStreamToFile(in, targetFile);
        } catch (Exception e) {
            return null;
        }
        return Excel.createFile("证照导入模板", targetFile, "default.btl", map);
    }
}
